//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.server;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tv.dyndns.kishibe.client.packet.PacketProblemData;

public class ServiceTopPage extends HttpServlet {
	private static final long serialVersionUID = -1443513445767345019L;
	private static final String PREFIX = "<html>\n<head>\n<title>QMAClone by nodchip(ノドチップ)</title>\n<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"QMAClone.css\">\n<link rel='alternate' type='application/rss+xml' title='QMAClone RSSフィード' href='rss.xml' />\n<link rel='alternate' type='application/atom+xml' title='QMAClone Atomフィード' href='rss.xml?rssVersion=atom03' />\n</head>\n\n<body>\n<iframe src=\"javascript:''\" id=\"__gwt_historyFrame\" style=\"width: 0; height: 0; border: 0\"></iframe>\n\n<script type=\"text/javascript\" language=\"javascript\" src=\"tv.dyndns.kishibe.QMAClone.nocache.js\"></script>\n\n<h1 id=\"title\" align=\"right\">QMAClone by nodchip(ノドチップ)</h1>\n\n<div id=\"slot\" style=\"width: 100%; height: 100%;\"></div>\n<div id=\"sound\" style=\"width: 0px; height: 0px\"></div>\n<div id=\"position_selecter\"></div>\n<div id=\"click_canvas\"></div>\n\n<div style='visibility: hidden'>\n";
	private static final String SURFIX = "</div>\n\n</body>\n</html>\n";
	private static final String[] WORDS = { "安い", "自動車", "保険", "ファースト", "サーバー", "自動車", "即日", "キャッシング", "シティ", "カード", "ノー", "ローン", "不動産", "担保", "クレジット", "融資", "オンライン", "契約", "不動産", "バンク", "法人", "サラリー", "投資", "減税", "医者", "結婚", "クオーク", "google", "アド", "ワーズ", "広告", "ビザ", "ワールド", "プレゼント" };
	private static final int MAX_ITEMS = 100;
	private final String[] words = createWords();
	private final transient Runnable runnableUpdate = new Runnable() {
		public void run() {
			update();
		}
	};
	private byte[] body;
	private final Random random = new Random();

	public ServiceTopPage() {
		update();
		ThreadPool.getInstance().addHourTask(runnableUpdate);
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		final OutputStream outputStream = resp.getOutputStream();
		outputStream.write(body);
		outputStream.close();
	}

	private void update() {
		final StringBuilder b = new StringBuilder();
		b.append(PREFIX);

		final int numberOfWords = random.nextInt(3) + 1;
		final StringBuilder q = new StringBuilder();
		for (int i = 0; i < numberOfWords; ++i) {
			if (i != 0) {
				q.append(" ");
			}
			q.append(words[random.nextInt(words.length)]);
		}

		int counter = 0;

		final PacketProblemData[] adsenseProblems = DatabaseFactory.getInstance().getAdsenseProblems(q.toString());
		for (PacketProblemData problemData : adsenseProblems) {
			if (counter++ == MAX_ITEMS) {
				break;
			}

			final String sentence = problemData.sentence;
			final String note = problemData.note;
			final String[] choices = problemData.choice;
			final String[] answers = problemData.answer;

			b.append("<div>\n");

			b.append("\t<div>").append(sentence).append("</div>\n");

			b.append("\t<div>");
			for (String choice : choices) {
				if (choice != null && !choice.isEmpty()) {
					b.append("<span>").append(choice).append("</span>");
				}
			}
			for (String answer : answers) {
				if (answer != null && !answer.isEmpty()) {
					b.append("<span>").append(answer).append("</span>");
				}
			}
			b.append("</div>\n");

			if (note != null && !note.isEmpty()) {
				b.append("\t<div>").append(note).append("</div>\n");
			}

			b.append("</div>\n");
		}

		b.append(SURFIX);

		try {
			body = b.toString().getBytes("utf-8");
		} catch (Exception e) {
		}
	}

	private String[] createWords() {
		final Set<String> set = new HashSet<String>();
		for (String word : WORDS) {
			set.add(word);
		}

		return set.toArray(new String[0]);
	}
}
